
package com.example.demo.util.rsa;

import com.example.demo.util.TextUtils;

import javax.crypto.Cipher;

import java.security.*;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by LG on 2018/9/21.
 */

public class RSAUtils {
    /**
     * 秘钥默认长度
     */
    static final int DEFAULT_KEY_SIZE = 2048;

    /**
     * 当前秘钥支持加密的最大字节数
     */
    static final int DEFAULT_BUFFERSIZE = (DEFAULT_KEY_SIZE / 8) - 11;

    /**
     * app请求参数进行解密,(公钥解密快)
     */
    public static final String KEY_STR_PUBLIC_REQUEST = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAqyEujS7bcHk8" +
            "+LX3gBBtw0JGTJzV7FNqdXBsNEjRl6SC9FHhQXfAk4tzsC5U5zwps+o2OFcxEuj6B"
            + "+SrgzbD1ciUafeshmqfpMZgUvrO/3tvyfDuPDaL8m+Xc8aXPXaMxPtCTi2boqER8PORJ69elZ/82AYVelHkhewK+Oo7b+PjEEklQm+rjk7YnqGnj1ZwC2+YJGHPg6"
            + "+BDrZNaMaiWl7AIzQCFBY26pLAyVslCBdfGNgx83ebZ9l1GXyrMtmBKLLSeDFk2lTzZlQch9Daong9+urIjwKdzX3rRIV+hbGPOATPmhfyb79b"
            + "/YPlKcgI4TCXYw4Vsa/DeycEOhR7swIDAQAB";

    /**
     * 给响应的报文加密,(公钥加密快)
     */
    public static final String KEY_STR_PUBLIC_RESPONSE = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAr8o46m"
            + "/qFqM0gGc5jwKBnhbIhKtLuIZTF51iiYt5L86BH4d7nhskV2nW48OaScOFQ4NdrJyfeOrUMxRvSalMAeXPX825zoVYwLkoPXAR1TkZ4Vj2iR6axBVsbTviJo"
            + "+PoP1VZFOINjklca0hXGTuRgz1xWt6RCagfnmPItuubmymf+8X3bLhdYQY2MOidDB7UrL8QuDNra"
            + "+4j50TJT6AhEG8DxIq1LCJEdVpQsfkrxFhfOhSXITACXGCTDUPw/Zb7p6s8BQOdnAvyoxWxNWYkmiutM67sOfBvHai2DB7Bu11pS95sYNd9VMJpAKfL"
            + "+W9zLaWkLcKGnavZDZ9ONpVhQIDAQAB";

    /**
     * 随机生成RSA密钥对
     *
     * @param keyLength 密钥长度，范围：512～2048 一般1024
     * @return
     */
    static KeyPair generateRSAKeyPair(int keyLength) {
        try {
            KeyPairGenerator kpg = KeyPairGenerator.getInstance(RSADecryptUtils.RSA);
            kpg.initialize(keyLength);
            return kpg.genKeyPair();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 将字符串形式的公钥转换为公钥对象
     *
     * @param strKey
     * @return
     */

    static PublicKey strKey2PublicKey(String strKey) {
        return RSADecryptUtils.strKey2PublicKey(strKey);
    }

    /**
     * 将字符串形式的私钥，转换为私钥对象
     *
     * @param strKey
     * @return
     */

    static PrivateKey strKey2PrivateKey(String strKey) {
        if (TextUtils.isEmpty(strKey)) {
            return null;
        }
        PrivateKey _PrivateKey = null;
        byte[] keyBytes = Base64.decode(strKey, Base64.DEFAULT);
        PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(keyBytes);
        try {
            KeyFactory keyFactory = KeyFactory.getInstance("RSA");
            _PrivateKey = keyFactory.generatePrivate(keySpec);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (InvalidKeySpecException e) {
            e.printStackTrace();
        } finally {
            return _PrivateKey;
        }
    }

    /**
     * 用公钥对字符串进行加密
     *
     * @param data 原文
     */
    static byte[] encryptByPublicKey(byte[] data, byte[] publicKey) throws Exception {
        if (data == null || publicKey == null) {
            return null;
        }
        // 得到公钥
        X509EncodedKeySpec keySpec = new X509EncodedKeySpec(publicKey);
        KeyFactory kf = KeyFactory.getInstance(RSADecryptUtils.RSA);
        PublicKey keyPublic = kf.generatePublic(keySpec);
        // 加密数据
        Cipher cp = Cipher.getInstance(RSADecryptUtils.ECB_PKCS1_PADDING);
        cp.init(Cipher.ENCRYPT_MODE, keyPublic);
        return cp.doFinal(data);
    }

    /**
     * 公钥分段解密
     *
     * @param encrypted 待解密数据
     * @param publicKey 密钥
     */
    static byte[] decryptByPublicKeyForSpilt(byte[] encrypted, byte[] publicKey) throws Exception {
        return RSADecryptUtils.decryptByPublicKeyForSpilt(encrypted, publicKey);
    }

    /**
     * 私钥加密
     *
     * @param data       待加密数据
     * @param privateKey 密钥
     * @return byte[] 加密数据
     */
    static byte[] encryptByPrivateKey(byte[] data, byte[] privateKey) throws Exception {
        if (data == null || privateKey == null) {
            return null;
        }
        // 得到私钥
        PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(privateKey);
        KeyFactory kf = KeyFactory.getInstance(RSADecryptUtils.RSA);
        PrivateKey keyPrivate = kf.generatePrivate(keySpec);
        // 数据加密
        Cipher cipher = Cipher.getInstance(RSADecryptUtils.ECB_PKCS1_PADDING);
        cipher.init(Cipher.ENCRYPT_MODE, keyPrivate);
        return cipher.doFinal(data);
    }

    /**
     * 使用私钥进行解密
     */
    static byte[] decryptByPrivateKey(byte[] encrypted, byte[] privateKey) throws Exception {
        if (encrypted == null || privateKey == null) {
            return null;
        }
        // 得到私钥
        PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(privateKey);
        KeyFactory kf = KeyFactory.getInstance(RSADecryptUtils.RSA);
        PrivateKey keyPrivate = kf.generatePrivate(keySpec);

        // 解密数据
        Cipher cp = Cipher.getInstance(RSADecryptUtils.ECB_PKCS1_PADDING);
        cp.init(Cipher.DECRYPT_MODE, keyPrivate);
        byte[] arr = cp.doFinal(encrypted);
        return arr;
    }

    /**
     * 用公钥对字符串进行分段加密
     */
    static byte[] encryptByPublicKeyForSpilt(byte[] data, byte[] publicKey) throws Exception {
        if (data == null || publicKey == null) {
            return null;
        }
        int dataLen = data.length;
        if (dataLen <= DEFAULT_BUFFERSIZE) {
            return encryptByPublicKey(data, publicKey);
        }
        List<Byte> allBytes = new ArrayList<>(2048);
        int bufIndex = 0;
        int subDataLoop = 0;
        byte[] buf = new byte[DEFAULT_BUFFERSIZE];
        for (int i = 0; i < dataLen; i++) {
            buf[bufIndex] = data[i];
            if (++bufIndex == DEFAULT_BUFFERSIZE || i == dataLen - 1) {
                subDataLoop++;
                if (subDataLoop != 1) {
                    for (byte b : RSADecryptUtils.DEFAULT_SPLIT) {
                        allBytes.add(b);
                    }
                }
                byte[] encryptBytes = encryptByPublicKey(buf, publicKey);
                for (byte b : encryptBytes) {
                    allBytes.add(b);
                }
                bufIndex = 0;
                if (i == dataLen - 1) {
                    buf = null;
                } else {
                    buf = new byte[Math.min(DEFAULT_BUFFERSIZE, dataLen - i - 1)];
                }
            }
        }
        byte[] bytes = new byte[allBytes.size()];
        {
            int i = 0;
            for (Byte b : allBytes) {
                bytes[i++] = b.byteValue();
            }
        }
        return bytes;
    }

    /**
     * 分段加密
     *
     * @param data       要加密的原始数据
     * @param privateKey 秘钥
     */
    static byte[] encryptByPrivateKeyForSpilt(byte[] data, byte[] privateKey) throws Exception {
        if (data == null || privateKey == null) {
            return null;
        }
        int dataLen = data.length;
        if (dataLen <= DEFAULT_BUFFERSIZE) {
            return encryptByPrivateKey(data, privateKey);
        }
        List<Byte> allBytes = new ArrayList<Byte>(2048);
        int bufIndex = 0;
        int subDataLoop = 0;
        byte[] buf = new byte[DEFAULT_BUFFERSIZE];
        for (int i = 0; i < dataLen; i++) {
            buf[bufIndex] = data[i];
            if (++bufIndex == DEFAULT_BUFFERSIZE || i == dataLen - 1) {
                subDataLoop++;
                if (subDataLoop != 1) {
                    for (byte b : RSADecryptUtils.DEFAULT_SPLIT) {
                        allBytes.add(b);
                    }
                }
                byte[] encryptBytes = encryptByPrivateKey(buf, privateKey);
                for (byte b : encryptBytes) {
                    allBytes.add(b);
                }
                bufIndex = 0;
                if (i == dataLen - 1) {
                    buf = null;
                } else {
                    buf = new byte[Math.min(DEFAULT_BUFFERSIZE, dataLen - i - 1)];
                }
            }
        }
        byte[] bytes = new byte[allBytes.size()];
        {
            int i = 0;
            for (Byte b : allBytes) {
                bytes[i++] = b.byteValue();
            }
        }
        return bytes;
    }

    /**
     * 使用私钥分段解密
     */
    static byte[] decryptByPrivateKeyForSpilt(byte[] encrypted, byte[] privateKey)
            throws Exception {
        if (encrypted == null || privateKey == null) {
            return null;
        }
        int splitLen = RSADecryptUtils.DEFAULT_SPLIT.length;
        if (splitLen <= 0) {
            return decryptByPrivateKey(encrypted, privateKey);
        }
        int dataLen = encrypted.length;
        List<Byte> allBytes = new ArrayList<>(1024);
        int latestStartIndex = 0;
        for (int i = 0; i < dataLen; i++) {
            byte bt = encrypted[i];
            boolean isMatchSplit = false;
            if (i == dataLen - 1) {
                // 到data的最后了
                byte[] part = new byte[dataLen - latestStartIndex];
                System.arraycopy(encrypted, latestStartIndex, part, 0, part.length);
                byte[] decryptPart = decryptByPrivateKey(part, privateKey);
                for (byte b : decryptPart) {
                    allBytes.add(b);
                }
                latestStartIndex = i + splitLen;
                i = latestStartIndex - 1;
            } else if (bt == RSADecryptUtils.DEFAULT_SPLIT[0]) {
                // 这个是以split[0]开头
                if (splitLen > 1) {
                    if (i + splitLen < dataLen) {
                        // 没有超出data的范围
                        for (int j = 1; j < splitLen; j++) {
                            if (RSADecryptUtils.DEFAULT_SPLIT[j] != encrypted[i + j]) {
                                break;
                            }
                            if (j == splitLen - 1) {
                                // 验证到split的最后一位，都没有break，则表明已经确认是split段
                                isMatchSplit = true;
                            }
                        }
                    }
                } else {
                    // split只有一位，则已经匹配了
                    isMatchSplit = true;
                }
            }
            if (isMatchSplit) {
                byte[] part = new byte[i - latestStartIndex];
                System.arraycopy(encrypted, latestStartIndex, part, 0, part.length);
                byte[] decryptPart = decryptByPrivateKey(part, privateKey);
                for (byte b : decryptPart) {
                    allBytes.add(b);
                }
                latestStartIndex = i + splitLen;
                i = latestStartIndex - 1;
            }
        }
        byte[] bytes = new byte[allBytes.size()];
        {
            int i = 0;
            for (Byte b : allBytes) {
                bytes[i++] = b.byteValue();
            }
        }
        return bytes;
    }

    // /**
    // * RSA公钥加密(速度快)
    // *
    // * @return
    // */
    // public static String encryptPublic(String plainText) {
    // return encryptPublic(RSADecryptUtils.KEY_STR_PUBLIC, plainText);
    // }

    /**
     * RSA公钥加密(速度快)
     *
     * @return
     */
    public static String encryptPublic(String key, String plainText) {
        if (plainText == null) {
            return null;
        }
        byte[] encryptBytes = new byte[0];
        try {
            PublicKey _PublicKey = RSADecryptUtils.strKey2PublicKey(key);
            if (_PublicKey == null) {
                return null;
            }
            encryptBytes = encryptByPublicKeyForSpilt(plainText.getBytes(),
                    _PublicKey.getEncoded());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return Base64.encodeToString(encryptBytes, Base64.DEFAULT);
    }

    public static String encryptPublicDef(String plainText) {
        return encryptPublic(RSAUtils.KEY_STR_PUBLIC_RESPONSE, plainText);
    }
    // /**
    // * RSA私钥加密(速度慢)
    // *
    // * @return
    // */
    // public static String encryptPrivate(String plainText) {
    // return encryptPrivate(KEY_STR_PRIVATE_DEFAULT, plainText);
    // }

    /**
     * RSA私钥加密(速度慢)
     *
     * @return
     */
    public static String encryptPrivate(String key, String plainText) {
        if (plainText == null) {
            return null;
        }
        byte[] encryptBytes2 = new byte[0];
        try {
            PrivateKey _PrivateKey = strKey2PrivateKey(key);
            if (_PrivateKey == null) {
                return null;
            }
            encryptBytes2 = encryptByPrivateKeyForSpilt(plainText.getBytes(),
                    _PrivateKey.getEncoded());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return Base64.encodeToString(encryptBytes2, Base64.DEFAULT);
    }

    // /**
    // * RSA私钥解密(速度慢)
    // *
    // * @return
    // */
    // public static String decryptPrivate(String encryptText) {
    // return decryptPrivate(KEY_STR_PRIVATE_DEFAULT, encryptText);
    // }

    /**
     * RSA私钥解密(速度慢)
     *
     * @return
     */
    public static String decryptPrivate(String key, String encryptText) {
        if (TextUtils.isEmpty(encryptText)) {
            return null;
        }
        byte[] encryptBytes2 = new byte[0];
        try {
            PrivateKey _PrivateKey = strKey2PrivateKey(key);
            if (_PrivateKey == null) {
                return null;
            }
            encryptBytes2 = decryptByPrivateKeyForSpilt(Base64.decode(encryptText, Base64.DEFAULT),
                    _PrivateKey.getEncoded());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new String(encryptBytes2);
    }

    /**
     * RSA公钥解密(速度快)
     *
     * @return
     */
    // public static String decryptPublic(String encryText) {
    // return RSADecryptUtils.decryptPublic(encryText);
    // }

    /**
     * RSA公钥解密(速度快)
     *
     * @return
     */
    public static String decryptPublic(String key, String encryText) {
        return RSADecryptUtils.decryptPublic(key, encryText);
    }

    public static String decryptPublicDef(String encryText) {
        return RSADecryptUtils.decryptPublic(RSAUtils.KEY_STR_PUBLIC_REQUEST, encryText);
    }
    // 测试代码
    // static RSAPublicKey publicKey;
    // static RSAPrivateKey privateKey;
    //
    // static {
    // KeyPair keyPair = RSAUtils.generateRSAKeyPair(RSAUtils.DEFAULT_KEY_SIZE);
    // // 公钥
    // publicKey = (RSAPublicKey) keyPair.getPublic();
    // // 私钥
    // privateKey = (RSAPrivateKey) keyPair.getPrivate();
    // }
}
